package com.blog.service.impl;

import com.blog.entity.User;
import com.blog.repository.UserRepository;
import com.blog.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElse(null);
    }

    @Override
    @Transactional
    public User createUser(String username, String password, boolean isAdmin) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setRole(isAdmin ? "ROLE_ADMIN" : "ROLE_USER");
        return userRepository.save(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && "ROLE_ADMIN".equals(user.getRole());
    }

    @Override
    public boolean existsByUsername(String username) {
        logger.debug("检查用户是否存在: {}", username);
        Optional<User> userOptional = userRepository.findByUsername(username);
        boolean exists = userOptional.isPresent();
        logger.debug("用户 {} {}", username, exists ? "存在" : "不存在");
        return exists;
    }

    @Override
    public String addUser(User user) {
        try {
            if (existsByUsername(user.getUsername())) {
                return "用户已存在";
            }
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            user.setRole("ROLE_USER"); // 默认角色
            userRepository.save(user);
            return "注册成功";
        } catch (Exception e) {
            logger.error("注册用户失败: {}", e.getMessage(), e);
            return "注册失败: " + e.getMessage();
        }
    }

    @Override
    public boolean validatePassword(String username, String password) {
        logger.debug("开始验证用户密码, 用户名: {}", username);

        Optional<User> userOptional = userRepository.findByUsernameCustomQuery(username);

        if (userOptional.isEmpty()) {
            logger.warn("用户不存在: {}", username);
            return false;
        }

        User user = userOptional.get();
        logger.debug("找到用户: {}, 开始验证密码", username);

        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (!matches) {
            logger.warn("密码不匹配, 用户名: {}", username);
        } else {
            logger.debug("密码验证成功, 用户名: {}", username);
        }
        return matches;
    }

    @Override
    public String getUserRole(String username) {
        logger.debug("获取用户角色, 用户名: {}", username);
        User user = findByUsername(username);
        if (user == null) {
            logger.warn("获取角色失败，用户不存在: {}", username);
            return null;
        }
        String role = user.getRole();
        logger.debug("用户 {} 的角色是: {}", username, role);
        return role;
    }
}